<?php

namespace adminmatrix\plugin\command\migrate;

use adminmatrix\plugin\command\Migrate;
use think\console\input\Option as InputOption;
use think\console\Input;
use think\console\Output;

class Status extends Migrate
{
    protected function configure()
    {
        $this->setName('plugin:migrate_status')
            ->addOption('app', '-a', InputOption::VALUE_OPTIONAL, '插件名')
            ->setDescription('查询插件数据库迁移状态');
            $this->addOption('connection', 'c', InputOption::VALUE_REQUIRED, 'The database connection to use.');

    }

    protected function execute(Input $input, Output $output)
    {
        $pluginName = $input->getOption('app');
        if (!$pluginName) {
            $output->error('请指定插件名 --app=插件名');
            return;
        }
        $this->pluginName = $pluginName;

        $this->printStatus();
    }

    protected function printStatus()
    {
        $output     = $this->output;
        $migrations = [];

        if (count($this->getMigrations())) {
            $output->writeln('');
            $output->writeln(' Status  Migration ID    Started              Finished             Migration Name  ');
            $output->writeln('------------------------------------------------------------------------------------');

            $versions      = $this->getVersionLog();
            $maxNameLength = $versions ? max(array_map(function ($version) {
                return strlen($version['migration_name']);
            }, $versions)) : 0;

            foreach ($this->getMigrations() as $migration) {
                $version = array_key_exists($migration->getVersion(), $versions) ? $versions[$migration->getVersion()] : false;
                if ($version) {
                    $status = '     <info>up</info> ';
                } else {
                    $status = '   <error>down</error> ';
                    $version = [];
                    $version['start_time'] = $version['end_time'] = $version['breakpoint'] = '';
                }
                $maxNameLength = max($maxNameLength, strlen($migration->getName()));

                $output->writeln(sprintf('%s %14.0f  %19s  %19s    <comment>%s</comment>', $status, $migration->getVersion(), $version['start_time'], $version['end_time'], $migration->getName() ));

                if ($version && $version['breakpoint']) {
                    $output->writeln('         <error>BREAKPOINT SET</error>');
                }
            }
        } else {
            $output->writeln('');
            $output->writeln('There are no available migrations. Try creating one using the <info>create</info> command.');
        }
        $output->writeln('');
    }
} 